 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=113 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Construct Object using class name
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='forName,newInstance,no&#045;argument constructor,reflection,text,constructor,generator,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Construct Object using class name</div>

<div class='main-body'>
 
<br>If a class has a no-argument constructor, then creating an object from
its package-qualified class name is done using <tt>Class.<a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#forName(java.lang.String)">forName</a></tt>
and
<tt>Class.<a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()">newInstance</a></tt>.
(An example of a package-qualified class name is "<tt>java.lang.Integer</tt>".)
<p>If arguments need to be passed to the constructor, then <tt>Class.<a href="http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getConstructor(java.lang.Class...)">getConstructor</a></tt>
and&nbsp; <tt>Constructor.<a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Constructor.html#newInstance(java.lang.Object...)">newInstance</a></tt>
may be used instead.

<p><b>Example</b>

<p>Here, the user inputs a package-qualified class name on the command
line, a corresponding <tt>Object</tt> is created and cast to the expected
type (here, <tt>Interpreter</tt>), and then used in the rest of the program
as any other object.

<p>This scenario is the most common use of reflection - to instantiate
a class whose generic type is known at design-time, but whose implementation
is not. An <a href="TopicAction8aa5-2.html">Abstract Factory</a> may use this technique,
for example, to create a factory object using a configured class name.
Other uses of reflection are rather rare, and appear mostly in special-purpose
programs.
<br>
<PRE>

<span class='keyword'>import</span> java.io.*;
<span class='keyword'>import</span> java.util.*;

<span class='comment'>/**
* Sends text back and forth between the command line and an
* Interpreter.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Console {

  <span class='comment'>/**
  * Build and launch a specific &lt;code&gt;Interpreter&lt;/code&gt;, whose
  * package-qualified name is passed in on the command line.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... aArguments) {
    <span class='keyword'>try</span> {
      Class theClass  = Class.forName(aArguments[<span class='literal'>0</span>]);
      Interpreter interpreter = (Interpreter)theClass.newInstance();
      Console console = <span class='keyword'>new</span> Console(interpreter);
      console.run();
    }
    <span class='keyword'>catch</span> ( ClassNotFoundException ex ){
      System.err.println( ex + <span class='literal'>" Interpreter class must be in class path."</span>);
    }
    <span class='keyword'>catch</span>( InstantiationException ex ){
      System.err.println( ex + <span class='literal'>" Interpreter class must be concrete."</span>);
    }
    <span class='keyword'>catch</span>( IllegalAccessException ex ){
      System.err.println( ex + <span class='literal'>" Interpreter class must have a no-arg constructor."</span>);
    }
  }

  <span class='keyword'>public</span> Console( Interpreter aInterpreter ) {
    <span class='keyword'>if</span> (aInterpreter == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Cannot be null."</span>);
    }
    fInterpreter = aInterpreter;
  }

  <span class='comment'>/**
  * Display a prompt, wait for a full line of input, and then parse
  * the input using an Interpreter.
  *
  * Exit when &lt;code&gt;Interpreter.parseInput&lt;/code&gt; returns true.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> run() {
    display( fInterpreter.getHelloPrompt() );

    <span class='comment'>//pass each line of input to fInterpreter, and display
</span>    <span class='comment'>//fInterpreter's result
</span>    InputStreamReader inputStreamReader = <span class='keyword'>new</span> InputStreamReader ( System.in );
    BufferedReader stdin = <span class='keyword'>new</span> BufferedReader ( inputStreamReader );
    <span class='keyword'>boolean</span> hasRequestedQuit = <span class='keyword'>false</span>;
    String line = <span class='keyword'>null</span>;
    List result = <span class='keyword'>new</span> ArrayList();
    <span class='keyword'>try</span> {
      <span class='keyword'>while</span> (!hasRequestedQuit) {
        line  = stdin.readLine();
        <span class='comment'>//note that "result" is passed as an "out" parameter
</span>        hasRequestedQuit = fInterpreter.parseInput( line, result );
        display( result );
        result.clear();
      }
    }
    <span class='keyword'>catch</span> ( IOException ex ) {
      System.err.println(ex);
    }
    <span class='keyword'>finally</span> {
      display(fBYE);
      shutdown( stdin );
    }
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fBYE = <span class='literal'>"Bye."</span>;
  <span class='keyword'>private</span>  Interpreter fInterpreter;

  <span class='comment'>/**
  * Display some text to stdout.
  *
  * @param aText must have a toString method.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> display( Object aText ){
    System.out.print( aText.toString() );
    System.out.flush();
  }

  <span class='comment'>/**
  * Display a List of objects as text in stdout, in the order returned
  * by the iterator of aText.
  *
  * @param aText must contain objects which have a toString method.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>void</span> display( List aText ) {
    Iterator textIter = aText.iterator();
    <span class='keyword'>while</span> ( textIter.hasNext() ) {
      display( textIter.next() );
    }
  }

  <span class='keyword'>private</span> <span class='keyword'>void</span> shutdown( Reader aStdin ){
    <span class='keyword'>try</span> {
      aStdin.close();
    }
    <span class='keyword'>catch</span> ( IOException ex ){
      System.err.println(ex);
    }
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction83bb-2.html?Id=79'>Console input</a> <br>
 
  
  <a href='TopicAction8aa5-2.html?Id=128'>Abstract Factory</a> <br>
 
  
  <a href='TopicAction5a93-2.html?Id=237'>Plugin Factory</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='113'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=113 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:08 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
